package lvbu.wang.lvbuoperator.utils;

import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.ComponentName;
import android.content.Intent;
import android.content.ServiceConnection;
import android.graphics.Color;
import android.os.IBinder;
import android.support.v7.app.AlertDialog;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;

import com.dothantech.lpapi.LPAPI;
import com.dothantech.printer.IDzPrinter;
import com.qing.library.utils.ToastUtil;

import net.posprinter.posprinterface.IMyBinder;
import net.posprinter.posprinterface.TaskCallback;
import net.posprinter.service.PosprinterService;
import net.posprinter.utils.DataForSendToPrinterTSC;

import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;

import static android.content.Context.BIND_AUTO_CREATE;

public class PrintQrCode1Proxy {

    private void showToast(Object o) {
        ToastUtil.showShortToast(context, "" + o);
    }

    /*** IMyBinder接口，所有可供调用的连接和发送数据的方法都封装在这个接口内 ***/
    public static IMyBinder binder;
    //bindService的参数conn
    ServiceConnection conn = new ServiceConnection() {

        @Override
        public void onServiceDisconnected(ComponentName name) {
            showToast("打印服务启动失败");
        }

        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            //绑定成功
            binder = (IMyBinder) service;
        }
    };

    public PrintQrCode1Proxy(Activity context) {
        this.context = context;
        init();
    }

    private Activity context;

    private List<IDzPrinter.PrinterAddress> pairedPrinters = new ArrayList<>();

    private String txt;

    private void init() {
        if (binder == null) {
            //绑定service，获取ImyBinder对象
            Intent intent = new Intent(context, PosprinterService.class);
            context.bindService(intent, conn, BIND_AUTO_CREATE);
        }
    }

    public void print(String qrcode) {
        this.txt = qrcode;
        selectPrinterOnClick();
    }
    // 选择打印机的按钮事件
    private void selectPrinterOnClick() {
        BluetoothAdapter btAdapter = BluetoothAdapter.getDefaultAdapter();
        if (btAdapter == null) {
            ToastUtil.showShortToast(context, "当前设备不支持蓝牙！");
            return;
        }
        if (!btAdapter.isEnabled()) {
            ToastUtil.showShortToast(context, "蓝牙适配器未开启！");
            return;
        }
        //获取可配对蓝牙设备
        Set<BluetoothDevice> device = btAdapter.getBondedDevices();
        pairedPrinters = new ArrayList<>();
        for (BluetoothDevice b : device) {
            pairedPrinters.add(new IDzPrinter.PrinterAddress(b.getName(), b.getAddress(), null));
        }
//        String s = "DC:0D:30:7E:A1:C1";
        new AlertDialog.Builder(context).setTitle("选择已绑定的设备").setAdapter(new DeviceListAdapter(), (dialogInterface, i) -> {
            IDzPrinter.PrinterAddress printer = pairedPrinters.get(i);

            binder.ConnectBtPort(printer.macAddress, new TaskCallback() {

                @Override
                public void OnSucceed() {
                    binder.WriteSendData(new TaskCallback() {
                        @Override
                        public void OnSucceed() {
                            quit();
                            showToast("打印指令发送成功");
                        }

                        @Override
                        public void OnFailed() {
                            showToast("打印指令发送失败");
                        }
                    }, () -> {
                        ArrayList<byte[]> list = new ArrayList<byte[]>();
                        //在打印请可以先设置打印内容的字符编码类型，默认为gbk，请选择打印机可识别的类型，参看编程手册，打印代码页
                        DataForSendToPrinterTSC.setCharsetName("gbk");//不设置，默认为gbk
                        //通过工具类得到一个指令的byte[]数据,以文本为例
                        //首先得设置size标签尺寸,宽60mm,高30mm,也可以调用以dot或inch为单位的方法具体换算参考编程手册
                        byte[] data0 = DataForSendToPrinterTSC.sizeBymm(62, 30);
                        list.add(data0);
                        //设置Gap,同上
                        list.add(DataForSendToPrinterTSC.gapBymm(2, 0));

                        //清除缓存
                        list.add(DataForSendToPrinterTSC.cls());
                        list.add(DataForSendToPrinterTSC.speed(0.3));
                        //条码指令，参数：int x，x方向打印起始点；int y，y方向打印起始点；
                        //string font，字体类型；int rotation，旋转角度；
                        //int x_multiplication，字体x方向放大倍数
                        //int y_multiplication,y方向放大倍数
                        //string content，打印内容

                        //打印二维码
                        String[] ss = txt.split(" ");
                        for (int i = 0; i < ss.length; i++) {
                            list.add(DataForSendToPrinterTSC.text(3 + i * 36, 195, "2", 0, 1, 1, ss[i]));
                        }
                        for (int i = 0; i < ss.length; i++) {
                            list.add(DataForSendToPrinterTSC.text(258 + i * 36, 195, "2", 0, 1, 1, ss[i]));
                        }
//                    list.add(DataForSendToPrinterTSC.text(3, 190, "1", 0, 1, 1, txt));
//                    list.add(DataForSendToPrinterTSC.text(250, 190, "1", 0, 1, 1, txt));
                        list.add(DataForSendToPrinterTSC.qrCode(20, 8, "Q", 7, "A", 0, "M2", "S7", txt));
                        list.add(DataForSendToPrinterTSC.qrCode(275, 8, "Q", 7, "A", 0, "M2", "S7", txt));
                        //打印
                        list.add(DataForSendToPrinterTSC.print(1));
                        return list;
                    });
                }

                @Override
                public void OnFailed() {
                    showToast("打印机连接失败");
                    System.out.println("连接失败");
                }
            });
        }).show();
    }

    public void quit() {
        binder.DisconnectCurrentPort(new TaskCallback() {
            @Override
            public void OnSucceed() {
            }

            @Override
            public void OnFailed() {
            }
        });
    }

    // 用于填充打印机列表的Adapter
    private class DeviceListAdapter extends BaseAdapter {
        private TextView tv_name = null;

        @Override
        public int getCount() {
            return pairedPrinters.size();
        }

        @Override
        public Object getItem(int position) {
            return pairedPrinters.get(position);
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            if (convertView == null) {
                convertView = LayoutInflater.from(context).inflate(android.R.layout.simple_list_item_1, null);
            }
            tv_name = (TextView) convertView.findViewById(android.R.id.text1);

            if (pairedPrinters != null && pairedPrinters.size() > position) {
                IDzPrinter.PrinterAddress printer = pairedPrinters.get(position);
//                tv_name.setText(printer.shownName + "\n" + printer.macAddress);
                tv_name.setBackgroundColor(Color.parseColor("#f5f5f5"));
                tv_name.setText(printer.shownName);
                // tv_mac.setText();
            }

            return convertView;
        }
    }

}
